package com.xunyin.modules.couponnew.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xunyin.api.XunyinException;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.common.utils.QueryHelpPlus;
import com.xunyin.constant.Constants;
import com.xunyin.enums.*;
import com.xunyin.modules.couponnew.domain.MtCoupon;
import com.xunyin.modules.couponnew.domain.MtUserCoupon;
import com.xunyin.modules.couponnew.service.CouponService;
import com.xunyin.modules.couponnew.service.UserCouponService;
import com.xunyin.modules.couponnew.service.dto.CouponDto;
import com.xunyin.modules.couponnew.service.dto.MtCouponQueryCriteria;
import com.xunyin.modules.couponnew.service.dto.ReqCouponDto;
import com.xunyin.modules.couponnew.service.mapper.MtCouponGoodsMapper;
import com.xunyin.modules.couponnew.service.mapper.MtCouponMapper;
import com.xunyin.modules.couponnew.service.mapper.MtUserCouponMapper;
import com.xunyin.modules.mtstore.domain.MtStore;
import com.xunyin.modules.mtstore.domain.MtStoreRoom;
import com.xunyin.modules.mtstore.service.mapper.MtStoreMapper;
import com.xunyin.modules.mtstore.service.mapper.MtStoreRoomMapper;
import com.xunyin.pagination.PaginationRequest;
import com.xunyin.pagination.PaginationResponse;
import com.xunyin.utils.*;
import com.xunyin.web.ResponseObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 卡券业务实现类
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Service
@RequiredArgsConstructor
@Slf4j
//@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CouponServiceImpl extends BaseServiceImpl<MtCouponMapper, MtCoupon> implements CouponService {

    @Autowired
    private MtCouponMapper mtCouponMapper;

    @Autowired
    private MtStoreMapper mtStoreMapper;

    @Autowired
    private MtStoreRoomMapper mtStoreRoomMapper;

    @Autowired
    private MtUserCouponMapper mtUserCouponMapper;

    @Autowired
    private MtCouponGoodsMapper mtCouponGoodsMapper;

    @Autowired
    private UserCouponService userCouponService;

    /**
     * 分页查询券列表
     *
     * @param paginationRequest
     * @return
     */
    @Override
    public PaginationResponse<MtCoupon> queryCouponListByPagination(PaginationRequest paginationRequest) {
        Page<MtCoupon> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        LambdaQueryWrapper<MtCoupon> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(MtCoupon::getStatus, "D");

        String name = paginationRequest.getSearchParams().get("name") == null ? "" : paginationRequest.getSearchParams().get("name").toString();
        if (StringUtils.isNotBlank(name)) {
            lambdaQueryWrapper.like(MtCoupon::getName, name);
        }
        String status = paginationRequest.getSearchParams().get("status") == null ? "" : paginationRequest.getSearchParams().get("status").toString();
        if (StringUtils.isNotBlank(status)) {
            lambdaQueryWrapper.eq(MtCoupon::getStatus, status);
        }
        String groupId = paginationRequest.getSearchParams().get("groupId") == null ? "" : paginationRequest.getSearchParams().get("groupId").toString();
        if (StringUtils.isNotBlank(groupId)) {
            lambdaQueryWrapper.eq(MtCoupon::getGroupId, groupId);
        }
        String type = paginationRequest.getSearchParams().get("type") == null ? "" : paginationRequest.getSearchParams().get("type").toString();
        if (StringUtils.isNotBlank(type)) {
            lambdaQueryWrapper.eq(MtCoupon::getType, type);
        }
        String storeIds = paginationRequest.getSearchParams().get("storeIds") == null ? "" : paginationRequest.getSearchParams().get("storeIds").toString();
        if (StringUtils.isNotBlank(storeIds)) {
            lambdaQueryWrapper.eq(MtCoupon::getStoreIds, storeIds);
        }
        String storeIdList = paginationRequest.getSearchParams().get("storeIdList") == null ? "" : paginationRequest.getSearchParams().get("storeIdList").toString();
        if (StringUtils.isNotBlank(storeIdList)) {
            lambdaQueryWrapper.in(MtCoupon::getStoreIds, JSONArray.parseArray(storeIdList, Integer.class));
        }
        lambdaQueryWrapper.orderByDesc(MtCoupon::getId);
        List<MtCoupon> dataList = mtCouponMapper.selectList(lambdaQueryWrapper);

        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<MtCoupon> paginationResponse = new PaginationResponse(pageImpl, MtCoupon.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(dataList);

        return paginationResponse;
    }

    @Override
    public Map<String, Object> queryAll(MtCouponQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<MtCoupon> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public List<MtCoupon> queryAll(MtCouponQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(MtCoupon.class, criteria));
    }


    /**
     * 保存卡券信息
     *
     * @param reqCouponDto
     */
    @Override
    @Transactional
    //@OperationServiceLog(description = "保存卡券信息")
    public MtCoupon saveCoupon(ReqCouponDto reqCouponDto) throws ParseException {
        MtCoupon mtCoupon;

        if (reqCouponDto.getId() != null) {
            mtCoupon = mtCouponMapper.selectById(reqCouponDto.getId());
        } else {
            mtCoupon = new MtCoupon();
        }

        // C优惠券；P预存卡；T集次卡
        if (reqCouponDto.getType().equals("C") || reqCouponDto.getType().equals("P") || reqCouponDto.getType().equals("T")) {
            System.out.println("reqCouponDto.getBeginTime():" + reqCouponDto.getBeginTime());
            Date startTime = DateUtils.parseDate(reqCouponDto.getBeginTime());
            Date endTime = DateUtils.parseDate(reqCouponDto.getEndTime());
            if (endTime.before(startTime)) {
                // throw new BusinessCheckException("生效期结束时间不能早于开始时间");
                throw new XunyinException("生效期结束时间不能早于开始时间");
            }
        }

        mtCoupon.setGroupId(reqCouponDto.getGroupId());
        if (reqCouponDto.getType() != null) {
            mtCoupon.setType(reqCouponDto.getType());
        }

        if (reqCouponDto.getName() != null) {
            mtCoupon.setName(CommonUtilV.replaceXSS(reqCouponDto.getName()));
        }
        // 是否允许转赠
        if (reqCouponDto.getIsGive() != null) {
            mtCoupon.setIsGive(reqCouponDto.getIsGive().equals(1) ? true : false);
        }
        if (reqCouponDto.getPoint() != null) {
            mtCoupon.setPoint(reqCouponDto.getPoint());
        }
        if (mtCoupon.getPoint() == null) {
            mtCoupon.setPoint(0);
        }

        if (reqCouponDto.getLimitNum() != null) {
            mtCoupon.setLimitNum(reqCouponDto.getLimitNum());
        }
        if (mtCoupon.getLimitNum() == null) {
            mtCoupon.setLimitNum(1);
        }

        if (reqCouponDto.getReceiveCode() != null) {
            mtCoupon.setReceiveCode(reqCouponDto.getReceiveCode());
        }
        if (mtCoupon.getReceiveCode() == null) {
            mtCoupon.setReceiveCode("");
        }

        // 有效期(天数)
        if (reqCouponDto.getLimitDay() != null) {
            mtCoupon.setLimitDay(reqCouponDto.getLimitDay());
        }

        if (mtCoupon.getLimitDay() == null) {
            mtCoupon.setLimitDay(0);
        }

/*        mtCoupon.setDescription(reqCouponDto.getDescription());
        mtCoupon.setRemarks(reqCouponDto.getRemarks());*/

        // 美团点评套餐id
        if (reqCouponDto.getDealId() != null) {
            mtCoupon.setDealId(reqCouponDto.getDealId());
        }

        // 可用的星期
        mtCoupon.setAvailWeekdays(reqCouponDto.getAvailWeekdays());
        // 适用时间段
        mtCoupon.setAvailTimescale(reqCouponDto.getAvailTimescale());

        mtCoupon.setStoreIds(reqCouponDto.getStoreIds());
        // 适用房间（包厢）
        mtCoupon.setRoomIds(reqCouponDto.getRoomIds());
        // 设置小时数
        mtCoupon.setHourCount(reqCouponDto.getHourCount());
        // 可使用次数
        mtCoupon.setUseableCount(reqCouponDto.getUseableCount());
        // 每次可使用小时数
        mtCoupon.setEveryUseableHourCount(reqCouponDto.getEveryUseableHourCount());


        if (mtCoupon.getType().equals(CouponTypeEnum.TIMER.getKey())) {
            if (reqCouponDto.getTimerPoint() != null) {
                mtCoupon.setPoint(reqCouponDto.getTimerPoint());
            }
            if (reqCouponDto.getTimerReceiveCode() != null) {
                mtCoupon.setReceiveCode(reqCouponDto.getTimerReceiveCode());
            }
        }


        // mtCoupon.setGradeIds(reqCouponDto.getGradeIds());

        if (reqCouponDto.getSendNum() == null) {
            reqCouponDto.setSendNum(1);
        }

        if (mtCoupon.getType().equals(CouponTypeEnum.PRESTORE.getKey()) || mtCoupon.getType().equals(CouponTypeEnum.TIMER.getKey())) {
            mtCoupon.setSendWay(SendWayEnum.FRONT.getKey());
        } else {
            mtCoupon.setSendWay(reqCouponDto.getSendWay());
        }

        mtCoupon.setSendNum(reqCouponDto.getSendNum());

        if (reqCouponDto.getTotal() == null) {
            reqCouponDto.setTotal(0);
        }
        mtCoupon.setTotal(reqCouponDto.getTotal());

        // C优惠券；P预存卡；T集次卡
        if (reqCouponDto.getType().equals("C") || reqCouponDto.getType().equals("P") || reqCouponDto.getType().equals("T")) {
            mtCoupon.setBeginTime(DateUtils.parseDate(reqCouponDto.getBeginTime()));
            mtCoupon.setEndTime(DateUtils.parseDate(reqCouponDto.getEndTime()));
            mtCoupon.setExceptTime(CommonUtilV.replaceXSS(reqCouponDto.getExceptTime()));
        }

        mtCoupon.setDescription(CommonUtilV.replaceXSS(reqCouponDto.getDescription()));
        mtCoupon.setRemarks(CommonUtilV.replaceXSS(reqCouponDto.getRemarks()));
        mtCoupon.setInRule(CommonUtilV.replaceXSS(reqCouponDto.getInRule()));
        mtCoupon.setOutRule(CommonUtilV.replaceXSS(reqCouponDto.getOutRule()));
        mtCoupon.setApplyGoods(reqCouponDto.getApplyGoods());
        mtCoupon.setUseFor(reqCouponDto.getUseFor());

        if (null == reqCouponDto.getAmount()) {
            reqCouponDto.setAmount(new BigDecimal(0));
        }
        mtCoupon.setAmount(reqCouponDto.getAmount());
        String image = reqCouponDto.getImage();
        if (null == image || image.equals("")) {
            image = "";
        }

        mtCoupon.setImage(image);
        mtCoupon.setRemarks(CommonUtilV.replaceXSS(reqCouponDto.getRemarks()));

        if (reqCouponDto.getStatus() == null || StringUtil.isEmpty(reqCouponDto.getStatus())) {
            mtCoupon.setStatus(StatusEnum.ENABLED.getKey());
        } else {
            mtCoupon.setStatus(reqCouponDto.getStatus());
        }

        // 创建时间
        if (reqCouponDto.getId() == null) {
            mtCoupon.setCreateTime(new Date());
        }

        // 更新时间
        mtCoupon.setUpdateTime(new Date());

        // 操作人
        mtCoupon.setOperator(reqCouponDto.getOperator());

        if (mtCoupon.getId() == null) {
            this.save(mtCoupon);
        } else {
            mtCouponMapper.updateById(mtCoupon);
        }

        // MtCoupon couponInfo = mtCouponMapper.selectById(mtCoupon.getId());

        // 更新已下发的会员卡券有效期
/*        if (couponInfo.getId() != null && reqCouponDto.getEndTime() != null && StringUtil.isNotEmpty(reqCouponDto.getEndTime())) {
            mtUserCouponMapper.updateExpireTime(couponInfo.getId(), reqCouponDto.getEndTime());
        }*/

        // 适用商品
/*        if (reqCouponDto.getGoodsIds() != null) {
            String[] goodsIds = reqCouponDto.getGoodsIds().split(",");
            if (goodsIds.length > 0) {*/
        // 1.先删除
/*                List<MtCouponGoods> couponGoodsList = mtCouponGoodsMapper.getCouponGoods(couponInfo.getId());
                for (MtCouponGoods cg : couponGoodsList) {
                    mtCouponGoodsMapper.deleteById(cg.getId());
                }*/
        // 2.再添加
/*                for (int n = 0; n < goodsIds.length; n++) {
                    if (StringUtil.isNotEmpty(goodsIds[n])) {
                        MtCouponGoods mtCouponGoods = new MtCouponGoods();
                        mtCouponGoods.setCouponId(couponInfo.getId());
                        mtCouponGoods.setGoodsId(Integer.parseInt(goodsIds[n]));
                        mtCouponGoods.setStatus(StatusEnum.ENABLED.getKey());
                        mtCouponGoods.setCreateTime(new Date());
                        mtCouponGoods.setUpdateTime(new Date());
                        mtCouponGoodsMapper.insert(mtCouponGoods);
                    }
                }*/
/*            }
        }*/

        return mtCoupon;
    }

    /**
     * 获取卡券列表
     *
     * @param paramMap
     */
    @Override
    @Transactional
    public ResponseObject findCouponList(Map<String, Object> paramMap) {
        Integer pageNumber = paramMap.get("pageNumber") == null ? Constants.PAGE_NUMBER : Integer.parseInt(paramMap.get("pageNumber").toString());
        Integer pageSize = paramMap.get("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(paramMap.get("pageSize").toString());
        String status = paramMap.get("status") == null ? StatusEnum.ENABLED.getKey() : paramMap.get("status").toString();
        String type = paramMap.get("type") == null ? "" : paramMap.get("type").toString();
        Integer storeId = (paramMap.get("storeId") == null) ? 0 : Integer.parseInt(paramMap.get("storeId").toString());
        // 1表示查询 H小时卡;N次数卡 ,2表示查询 C优惠券
        Integer queryTypeScope = paramMap.get("queryTypeScope") == null ? 1 : Integer.parseInt(paramMap.get("queryTypeScope").toString());

        Integer changeType = (paramMap.get("changeType") == null) ? 0 : Integer.parseInt(paramMap.get("changeType").toString());


/*        Integer userId =  paramMap.get("userId") == null ? 0 : Integer.parseInt(paramMap.get("userId").toString());
        String needPoint =  paramMap.get("needPoint") == null ? "0" : paramMap.get("needPoint").toString();
        String sendWay =  paramMap.get("sendWay") == null ? "front" : paramMap.get("sendWay").toString();
        String sortType = paramMap.get("sortType") == null ? "createTime" : paramMap.get("sortType").toString();*/

        Page<MtCoupon> pageHelper = PageHelper.startPage(pageNumber, pageSize);
        LambdaQueryWrapper<MtCoupon> lambdaQueryWrapper = Wrappers.lambdaQuery();

        if (StringUtil.isNotEmpty(status)) {
            lambdaQueryWrapper.eq(MtCoupon::getStatus, status);
        }

        if (queryTypeScope == 1) {
            String types = "H,N";
            if(changeType==1){
                types = "H,N,C";
            }
            lambdaQueryWrapper.in(MtCoupon::getType, Arrays.asList(types.split(",")));
        } else if (queryTypeScope == 2) {
            lambdaQueryWrapper.eq(MtCoupon::getType, "C");
        }

        // 查询具体门店的卡券
        if (storeId > 0) {
            lambdaQueryWrapper.eq(MtCoupon::getStoreIds, storeId);
        }

/*        if (StringUtil.isNotEmpty(sendWay)) {
            lambdaQueryWrapper.eq(MtCoupon::getSendWay, sendWay);
        }*/
/*        if (StringUtil.isNotEmpty(type)) {
            lambdaQueryWrapper.eq(MtCoupon::getType, type);
        }*/
/*        if (Integer.parseInt(needPoint) > 0) {
            lambdaQueryWrapper.eq(MtCoupon::getPoint, 0);
        }*/

        lambdaQueryWrapper.orderByDesc(MtCoupon::getId);
        List<MtCoupon> dataList = mtCouponMapper.selectList(lambdaQueryWrapper);

        // 处理已过期
/*        int expireNum = 0;
        for (MtCoupon coupon : dataList) {
            if (coupon.getEndTime().before(new Date())) {
                coupon.setStatus(StatusEnum.EXPIRED.getKey());
                coupon.setUpdateTime(new Date());
                mtCouponMapper.updateById(coupon);
                expireNum++;
            }
        }*/

        // 星期列表
/*        WeekDayEnum[] weekDayEnum = WeekDayEnum.values();
        List<ParamDto> weekDayForList = new ArrayList<>();
        for (WeekDayEnum enumItem : weekDayEnum) {
            ParamDto paramDto = new ParamDto();
            paramDto.setKey(enumItem.getKey());
            paramDto.setName(enumItem.getValue());
            paramDto.setValue(enumItem.getKey());
            weekDayForList.add(paramDto);
        }*/


        List<CouponDto> content = new ArrayList<>();

        for (int i = 0; i < dataList.size(); i++) {
            CouponDto item = new CouponDto();
            //MtCoupon mtCoupon = dataList.get(i);



                // 可用星期转换显示
                String availWeekdays = dataList.get(i).getAvailWeekdays();
                if (availWeekdays == null || "".equals(availWeekdays)) {
                    dataList.get(i).setAvailWeekdays("无限制");
                } else {
                    String[] availWeekdaysArr = availWeekdays.split(",");
                    String tempAvailWeekdays = "";
                    for (String str : availWeekdaysArr) {
                        if (WeekDayEnum.MONDAY.getKey().equals(str)) {
                            tempAvailWeekdays += WeekDayEnum.MONDAY.getValue() + ",";
                        } else if (WeekDayEnum.TUESDAY.getKey().equals(str)) {
                            tempAvailWeekdays += WeekDayEnum.TUESDAY.getValue() + ",";
                        } else if (WeekDayEnum.WEDNESDAY.getKey().equals(str)) {
                            tempAvailWeekdays += WeekDayEnum.WEDNESDAY.getValue() + ",";
                        } else if (WeekDayEnum.THURSDAY.getKey().equals(str)) {
                            tempAvailWeekdays += WeekDayEnum.THURSDAY.getValue() + ",";
                        } else if (WeekDayEnum.FRIDAY.getKey().equals(str)) {
                            tempAvailWeekdays += WeekDayEnum.FRIDAY.getValue() + ",";
                        } else if (WeekDayEnum.SATURDAY.getKey().equals(str)) {
                            tempAvailWeekdays += WeekDayEnum.SATURDAY.getValue() + ",";
                        } else if (WeekDayEnum.WEEKDAY.getKey().equals(str)) {
                            tempAvailWeekdays += WeekDayEnum.WEEKDAY.getValue() + ",";
                        }
                    }
                    tempAvailWeekdays = tempAvailWeekdays.substring(0, tempAvailWeekdays.length() - 1);
                    if(changeType==0){
                        dataList.get(i).setAvailWeekdays(tempAvailWeekdays);
                    }else{
                        dataList.get(i).setAvailWeekdaysText(tempAvailWeekdays);
                    }

                }


            //if(changeType==0){
                // 适用时间段转换显示
                String availTimescale = dataList.get(i).getAvailTimescale();
                if (availTimescale == null || "".equals(availTimescale)) {
                    dataList.get(i).setAvailTimescale("无限制");
                } else {
                    String[] availTimescaleArr = availTimescale.split(",");
                    String tempAvailTimescale = "";
                    for (String str : availTimescaleArr) {
                        if (TimeScaleEnum.ONETOSIX.getKey().equals(str)) {
                            tempAvailTimescale += TimeScaleEnum.ONETOSIX.getValue() + ",";
                        } else if (TimeScaleEnum.SIXTOTWELVE.getKey().equals(str)) {
                            tempAvailTimescale += TimeScaleEnum.SIXTOTWELVE.getValue() + ",";
                        } else if (TimeScaleEnum.TWELVETOEIG.getKey().equals(str)) {
                            tempAvailTimescale += TimeScaleEnum.TWELVETOEIG.getValue() + ",";
                        } else if (TimeScaleEnum.EIGTOTWEFOUR.getKey().equals(str)) {
                            tempAvailTimescale += TimeScaleEnum.EIGTOTWEFOUR.getValue() + ",";
                        }
                    }

                    tempAvailTimescale = tempAvailTimescale.substring(0, tempAvailTimescale.length() - 1);
                    //dataList.get(i).setAvailTimescale(tempAvailTimescale);
                    if(changeType==0){
                        dataList.get(i).setAvailTimescale(tempAvailTimescale);
                    }else{
                        dataList.get(i).setAvailTimescaleText(tempAvailTimescale);
                    }

                }
            //}


            // 适用门店转换显示
            String storeIds = dataList.get(i).getStoreIds();
            if (storeIds == null || "".equals(storeIds)) {
                dataList.get(i).setStoreIds("无限制");
            } else {
                String[] storeIdsArr = storeIds.split(",");
                //List<String> ids = Arrays.asList(storeIdsArr);
                String tempstore = "";
                for (String id : storeIdsArr) {
                    // 根据门店id,获取门店名称
                    MtStore mtStore = mtStoreMapper.selectById(id);
                    tempstore += mtStore.getName() + ",";
                }
                tempstore = tempstore.substring(0, tempstore.length() - 1);
                dataList.get(i).setStoreIds(tempstore);
            }

            if(changeType==0){
                // 适用包厢转换显示
                String roomIds = dataList.get(i).getRoomIds();
                if (roomIds == null || "".equals(roomIds)) {
                    dataList.get(i).setRoomIds("无限制");
                } else {
                    String[] roomIdsArr = roomIds.split(",");
                    String tempRoom = "";
                    for (String id : roomIdsArr) {
                        MtStoreRoom mtStoreRoom = mtStoreRoomMapper.selectById(id);
                        tempRoom += mtStoreRoom.getStoreRoomName() + ",";
                    }
                    tempRoom = tempRoom.substring(0, tempRoom.length() - 1);
                    dataList.get(i).setRoomIds(tempRoom);
                }
            }

            BeanUtils.copyProperties(dataList.get(i), item);
            content.add(item);
        }
/*
        String baseImage = settingService.getUploadBasePath();
        for (int i = 0; i < dataList.size(); i++) {
            CouponDto item = new CouponDto();
            BeanUtils.copyProperties(dataList.get(i), item);
            item.setIsReceive(false);
            item.setImage(baseImage + item.getImage());

            // 是否领取，且领取量大于限制数
            List<String> statusList = Arrays.asList(UserCouponStatusEnum.UNUSED.getKey(), UserCouponStatusEnum.USED.getKey(), UserCouponStatusEnum.EXPIRE.getKey());
            List<MtUserCoupon> userCoupon = mtUserCouponMapper.getUserCouponListByCouponId(userId, item.getId(), statusList);
            if ((userCoupon.size() >= dataList.get(i).getLimitNum()) && (dataList.get(i).getLimitNum() > 0)) {
                item.setIsReceive(true);
                item.setUserCouponId(userCoupon.get(0).getId());
            }

            // 领取或预存数量
            CouponNumBean numData = mtUserCouponMapper.getPeopleNumByCouponId(item.getId());
            Long num;
            if (null == numData) {
                num = 0l;
            } else {
                num = numData.getNum();
            }
            item.setGotNum(num.intValue());

            // 剩余数量
            Integer leftNum = dataList.get(i).getTotal() - item.getGotNum();
            item.setLeftNum(leftNum >= 0 ? leftNum : 0);

            String sellingPoint = "";

            // 优惠券卖点
            if (item.getType().equals(CouponTypeEnum.COUPON.getKey())) {
                if (StringUtil.isNotEmpty(item.getOutRule()) && Integer.parseInt(item.getOutRule()) > 0) {
                    sellingPoint = "满" + item.getOutRule() + "可用";
                } else {
                    sellingPoint = "无门槛券";
                }
            }

            // 预存券卖点
            if (item.getType().equals(CouponTypeEnum.PRESTORE.getKey())) {
                if (StringUtil.isNotEmpty(item.getInRule())) {
                    String inRuleArr[] = item.getInRule().split(",");
                    if (inRuleArr.length > 0) {
                        for (int n = 0; n < inRuleArr.length; n++) {
                            String store[] = inRuleArr[n].split("_");
                            sellingPoint = "预存" + store[0] + "赠" + store[1];
                        }
                    }
                }
            }

            // 计次卡卖点
            if (item.getType().equals(CouponTypeEnum.TIMER.getKey()) && StringUtil.isNotEmpty(item.getOutRule())) {
                sellingPoint = "集满" + item.getOutRule() + "次即可";
            }

            item.setSellingPoint(sellingPoint);
            content.add(item);
        }*/

        PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<CouponDto> paginationResponse = new PaginationResponse(pageImpl, CouponDto.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(content);
        return new ResponseObject(200, "查询成功", paginationResponse);
    }

    /**
     * 根据ID获取券信息
     *
     * @param id 券ID
     */
    @Override
    public MtCoupon queryCouponById(Integer id) {
        return mtCouponMapper.selectById(id);
    }

    /**
     * 根据条件查询卡券
     * @param coupon
     * @return
     */
    public List<MtCoupon> queryCouponListByCondi(MtCoupon coupon) {
        LambdaQueryWrapper<MtCoupon> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (StringUtil.isNotEmpty(coupon.getIsNewGive())) {
            lambdaQueryWrapper.eq(MtCoupon::getIsNewGive, coupon.getIsNewGive());
        }
        if (StringUtil.isNotEmpty(coupon.getStoreIds())) {
            if(coupon.getStoreIds().length()>0){
                lambdaQueryWrapper.eq(MtCoupon::getStoreIds, coupon.getStoreIds());
            }
        }

        lambdaQueryWrapper.orderByDesc(MtCoupon::getId);
        List<MtCoupon> dataList = mtCouponMapper.selectList(lambdaQueryWrapper);
        return dataList;
    }

    /**
     * 删除卡券
     *
     * @param id       券ID
     * @param operator 操作人
     */
    @Override
    // @OperationServiceLog(description = "删除卡券")
    public void deleteCoupon(Long id, String operator) {
        MtCoupon couponInfo = this.queryCouponById(id.intValue());
        if (null == couponInfo) {
            return;
        }

        couponInfo.setStatus("D");

        // 修改时间
        couponInfo.setUpdateTime(new Date());

        // 操作人
        couponInfo.setOperator(operator);

        mtCouponMapper.updateById(couponInfo);

        return;
    }

    @Override
    public void sendCoupon(Integer couponId, Integer num, Integer userId, Integer storeId) {
        MtCoupon mtCoupon = mtCouponMapper.selectById(couponId);
        //List<MtCoupon> dataList = mtCouponMapper.selectList(lambdaQueryWrapper);
        if (mtCoupon != null) {
            String orderId = RandomUtil.getRandom(5);
            // 用户卡券(小时卡、次数卡)购买订单
            // 生成用户对应的卡券
            if (mtCoupon.getType().equals(CouponTypeEnum.HOUR.getKey())
                    || mtCoupon.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {

                for(int i=0;i<num;i++){

                    Map<String, Object> param = new HashMap<>();
                    param.put("couponId", mtCoupon.getId());
                    param.put("userId", userId);
                    param.put("orderId", "sendCoupon" + orderId);
                    param.put("storeId", storeId);
                    userCouponService.userBuyConpon(param);

                }

                // 生成用户对应的优惠券
            } else if (mtCoupon.getType().equals(CouponTypeEnum.COUPON.getKey())) {

                for(int i=0;i<num;i++){

                    userCouponService.buyCouponItem(orderId, mtCoupon.getId(), userId, storeId,"D");
                }

            }
        }
    }

    @Override
    public void sendCouponRefGive(Integer couponId, Integer num, Integer userId, Integer storeId,String refGive) {
        MtCoupon mtCoupon = mtCouponMapper.selectById(couponId);
        //List<MtCoupon> dataList = mtCouponMapper.selectList(lambdaQueryWrapper);
        if (mtCoupon != null) {
            String orderId = RandomUtil.getRandom(5);
            // 用户卡券(小时卡、次数卡)购买订单
            // 生成用户对应的卡券
            if (mtCoupon.getType().equals(CouponTypeEnum.HOUR.getKey())
                    || mtCoupon.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {

                for(int i=0;i<num;i++){

                    Map<String, Object> param = new HashMap<>();
                    param.put("couponId", mtCoupon.getId());
                    param.put("userId", userId);
                    param.put("orderId", "sendCoupon" + orderId);
                    param.put("storeId", storeId);
                    param.put("refGive", refGive);
                    userCouponService.userBuyConpon(param);
                }

                // 生成用户对应的优惠券
            } else if (mtCoupon.getType().equals(CouponTypeEnum.COUPON.getKey())) {

                for(int i=0;i<num;i++){
                    userCouponService.buyCouponItem(orderId, mtCoupon.getId(), userId, storeId,refGive);
                }

            }
        }
    }

    @Override
    public List<MtCoupon> queryCouponListByGroupId(Integer groupId) {
        return null;
    }

    @Override
    public String useCoupon(Integer userCouponId, Integer userId, Integer storeId, Integer orderId, BigDecimal amount, String remark) {
        return null;
    }

    @Override
    public void deleteUserCoupon(Integer id, String operator) {

    }

    @Override
    public void rollbackUserCoupon(Integer id, Integer userCouponId, String operator) {

    }

    @Override
    public MtUserCoupon queryUserCouponById(Integer userCouponId) {
        return null;
    }

    @Override
    public void removeUserCoupon(Long id, String uuid, String operator) {

    }

    @Override
    public boolean codeExpired(String code) {
        return false;
    }

    @Override
    public boolean isCouponEffective(MtCoupon coupon) {
        return false;
    }


    /**
     * 更新卡券（小时卡、次卡、优惠券）是否新注册用户赠送，0：表示否 1：表示是
     *
     * @param id       卡券ID
     * @param isNewGiveStatus   上线状态
     */
    @Override
    @Transactional
    //@OperationServiceLog(description = "更新卡券（小时卡、次卡、优惠券）是否新注册用户赠送")
    public void updateIsNewGiveStatus(Integer id, String isNewGiveStatus) {
        MtCoupon mtCoupon = this.getById(id);
        if (null == mtCoupon) {
            throw new XunyinException("该卡券不存在.");
        }
        mtCoupon.setIsNewGive(isNewGiveStatus);
        mtCoupon.setUpdateTime(new Date());
        mtCouponMapper.updateById(mtCoupon);
    }

    /**
     * 更新卡券（小时卡、次卡、优惠券）是否给推荐人赠送，A：是；D：否
     *
     * @param id       卡券ID
     * @param refGiveStatus   上线状态
     */
    @Override
    @Transactional
    //@OperationServiceLog(description = "更新卡券（小时卡、次卡、优惠券）是否给推荐人赠送，A：是；D：否")
    public void updateRefGiveStatus(Integer id, String refGiveStatus) {
        MtCoupon mtCoupon = this.getById(id);
        if (null == mtCoupon) {
            throw new XunyinException("该卡券不存在.");
        }
        mtCoupon.setRefGive(refGiveStatus);
        mtCoupon.setUpdateTime(new Date());
        mtCouponMapper.updateById(mtCoupon);
    }
}
